package com.glela.task;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.glela.common.util.Base64Util;
import com.glela.common.util.Config;
import com.glela.common.util.DateUtil;
import com.glela.common.util.HttpUtil;
import com.glela.common.util.MD5Utils;
import com.glela.goods.mapper.InventoryMapper;
import com.glela.goods.model.InventorySync;
import com.glela.platform.mapper.BaseRestrictionsMapper;

/**
 * 校妆对接库存Task
 * @author MaoZeYao
 */
public class InventoryTask {
	private static final Logger logger = LoggerFactory.getLogger(InventoryTask.class);

	private final String	appKey	= Config.getString("xz.appKey");
	private final String	secret	= Config.getString("xz.secret");
	private final String	method	= "inventory.query";
	private final String	url		= Config.getString("xz.sendOrder");

	@Autowired
	private InventoryMapper			inventoryMapper;
	@Autowired
	private BaseRestrictionsMapper	baseRestrictionsMapper;

	public int autoQueryInventory() {
		int start = baseRestrictionsMapper.selectInventoryLimit();
		if (start == 1) {
			return 0;
		}

		int page = 1;
		int pageSize = 1000;
		int startIndex = (page - 1) * pageSize;
		boolean flag = true;
		while (flag) {
			// List<Inventory> inventoryList = inventoryMapper.selectInventoryEntityByPage(startIndex, pageSize);
			List<InventorySync> inventoryList = inventoryMapper.selectAutoSyncInventoryByPage(startIndex, pageSize);
			flag = CollectionUtils.isNotEmpty(inventoryList);
			if (flag) {
				Map<String, Object> omsdataMap = new HashMap<>();
				for (InventorySync inventory : inventoryList) {
					// String result =
					// "{\"sku_no\":[\"9010010028\"],\"page_no\":1,\"page_size\":100,\"inventory_status\":\"normal\"}";
					String requestResult = "";
					try {
						// String skuNo = productMapper.selectproductNoById(inventory.getProductId());
						packageOmsData(omsdataMap, inventory.getProductBn());

						//						StringBuilder sb = new StringBuilder();
						//						sb.append("{\r\n");
						//						sb.append("\"method\":\"" + method + "\",\r\n");
						//						sb.append("\"timestamp\":\"" + DateUtil.getNow() + "\",\r\n");
						//						sb.append("\"app_key\":\"" + appKey + "\",\r\n");
						//						sb.append("\"sign\":\"" + sign + "\",\r\n");
						//						sb.append("\"data\":\"" + data + "\"\r\n}");
						//						logger.info("-------------->参数构造完成：" + sb.toString());

						requestResult = HttpUtil.doPost(JSON.toJSONString(omsdataMap), url, "application/json");
						int availableQty = outJson(requestResult);
						if (logger.isDebugEnabled()) {
							logger.error("同步库存-------------->  " + inventory.getProductBn() + "     返回有效库存值:" + availableQty);
						}
						if (availableQty == -1) {
							//							logger.info("-------------->未从校妆请求到数据，货号："+inventory.getProductBn());
						} else {
							//							logger.info("-------------->开始更新本地库存,数量："+availableQty);
							int updateStatus = inventoryMapper.updateLocalInventory(inventory.getId(), availableQty);
							if (updateStatus <= 0) {
								logger.error(" -----------> 库存查询失败 : 库存ID：" + inventory.getId());
							}
						}
					} catch (IOException e) {
						logger.error("库存查询失败，货号：{}:{} 结果：{}", inventory.getProductBn(), e.getMessage(), requestResult, e);
					}
				}
				startIndex = (++page - 1) * pageSize;
				//				logger.error("-------------->本次处理数据：" + inventoryList.size() + "条");
			}
		}
		//		logger.info("-------------->本次库存处理数据完成");
		return 0;
	}

	private void packageOmsData(Map<String, Object> omsdataMap, String... productBn) {
		omsdataMap.clear();

		Map<String, Object> paramsMap = new HashMap<>();
		paramsMap.put("sku_no", productBn);
		paramsMap.put("page_no", 1);
		paramsMap.put("page_size", 10);
		String data = Base64Util.encode(JSON.toJSONString(paramsMap));
		String sign = MD5Utils.encryptNoStart(data + secret);
		omsdataMap.put("method", method);
		omsdataMap.put("timestamp", DateUtil.getNow());
		omsdataMap.put("app_key", appKey);
		omsdataMap.put("sign", sign);
		omsdataMap.put("data", data);
	}

	/*public static void main(String[] args) {
		localTest();
	}
	
	public static void localTest() {
		String appKey = "29833924";
		String secret = "IKOoJGNC0swOw$!MCQ";
		String method = "inventory.query";
		String url = "http://s.skin79.com.cn/wms-sf/oms";
		String skuNo = "922196";
		String result = "{\"sku_no\":[\"" + skuNo + "\"],\"page_no\":1,\"page_size\":100}";
		String data = Base64Util.encode(result);
		String sign = MD5Utils.encryptNoStart(data + secret);
		StringBuffer sb = new StringBuffer();
		sb.append("{\r\n");
		sb.append("\"method\":\"" + method + "\",\r\n");
		sb.append("\"timestamp\":\"" + DateUtil.toString(new Date()) + "\",\r\n");
		sb.append("\"app_key\":\"" + appKey + "\",\r\n");
		sb.append("\"sign\":\"" + sign + "\",\r\n");
		sb.append("\"data\":\"" + data + "\"\r\n}");
		logger.info("-------------->参数构造完成：" + sb.toString());
		String requestResult = null;
		try {
			requestResult = HttpUtil.doPost(sb.toString(), url, "application/json");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(requestResult);
	}*/

	/**
	 * 解析校妆返回JSON
	 */
	protected int outJson(String jsonStr) {
		JSONObject objJson = JSONObject.parseObject(jsonStr);
		//TODO 未处理有分页情况		objJson.getBooleanValue("has_next");
		if ("00000".equals(objJson.get("code").toString())) {
			String data = objJson.get("data").toString();
			JSONObject dataJson = JSONObject.parseObject(data);
			JSONArray list = JSONArray.parseArray(dataJson.get("rows").toString());
			int availableQty = 0; // 可用库存
			if (list.iterator().hasNext()) {
				JSONObject qty = JSONObject.parseObject(list.iterator().next().toString());
				availableQty = qty.getIntValue("available_qty");
			}
			return availableQty;
		}
		return -1;
	}

}
